package org.szrcb.temu.SalesManage.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.szrcb.temu.SalesManage.Vo.ResultVO;
import org.szrcb.temu.SalesManage.po.SyncUserPo;
import org.szrcb.temu.SalesManage.po.WarehouseResult;
import org.szrcb.temu.SalesManage.po.subOrder;
import org.szrcb.temu.SalesManage.pojo.MallInfo;
import org.szrcb.temu.SalesManage.pojo.UserInfo;
import org.szrcb.temu.SalesManage.req.WarehouserReq;
import org.szrcb.temu.SalesManage.service.LoginService;
import org.szrcb.temu.SalesManage.service.MallInfoService;
import org.szrcb.temu.SalesManage.service.UserInfoService;
import org.szrcb.temu.SalesManage.utils.ResultVOUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private MallInfoService mallInfoService;

    @PostMapping("/login")
    public ResultVO<String> login(@RequestParam("userId") String userId, @RequestParam("cookie") String cookie) {
        int userCount = userInfoService.countUserInfo(userId);
        if (userCount == 0) {
            return ResultVOUtil.error(1,"该用户不存在");
        }
        String token = userInfoService.queryAccessToken(userId,cookie);
        return ResultVOUtil.success(token);
    }

    @PostMapping("/syncUserInfo")
    public ResultVO syncUserInfo(@RequestBody SyncUserPo po) {
        try {
            JSONObject userResultObject = null;
            boolean b = false;
            while (!b) {
                userResultObject = getUserInfoJson("https://seller.kuajingmaihuo.com/bg/quiet/api/mms/userInfo", po.getCookie());
                b = userResultObject.getObject("success", boolean.class);
            }

            //获取当前登录账号的用户信息
            UserInfo user = userResultObject.getObject("result", UserInfo.class);
            if (user == null) {
                ResultVOUtil.error(1, "用户信息为空");
            }
            //查询是否有当前用户信息并入库
            int userCount = userInfoService.countUserInfo(user.getUserId());
            if (userCount > 0) {
                userInfoService.updateUserInfo(user);
            } else {
                userInfoService.insertUserInfo(user);
            }
            //设置用户cookie,token
            int userTokenCount = userInfoService.countUserTokenInfo(po.getUserId());
            String token = SecureUtil.md5(po.getUserId() + System.currentTimeMillis());
            if (userTokenCount > 0) {
                //更新
                userInfoService.updateUserToken(po.getUserId(), po.getCookie(), token);
            } else {
                //插入
                userInfoService.insertUserToken(po.getUserId(), po.getCookie(), token);
            }
            //获取用户账号下的店铺信息
            List<MallInfo> malInfoList = user.getCompanyList().get(0).getMalInfoList();
            if (malInfoList == null || malInfoList.size() == 0) {
                ResultVOUtil.error(1, "账号下店铺为空或数量为0");
            }
            //更新店铺信息
            mallInfoService.deleteUserMallRel(user.getUserId());
            malInfoList.forEach(mallInfo -> {
                int mallInfoCount = mallInfoService.countMallInfoById(mallInfo.getMallId());
                if (mallInfoCount > 0) {
                    mallInfoService.updateMallInfo(mallInfo);
                } else {
                    mallInfo.setVipState(0);
                    mallInfoService.insertMallInfo(mallInfo);
                }
                //更新user_mall_rel关系表
                mallInfoService.updateUserMallRel(user.getUserId(), mallInfo.getMallId());
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVOUtil.success("success");
    }

    private JSONObject getUserInfoJson(String httpUrl, String cookie) {
        StringBuilder content = new StringBuilder();
        HttpURLConnection conn = null;
        BufferedReader br = null;
        try {
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Origin", "https://seller.kuajingmaihuo.com");
            conn.setRequestProperty("cookie", cookie);
            conn.connect();

            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;

            while ((inputLine = br.readLine()) != null) {
                content.append(inputLine);
            }
            br.close();
            conn.disconnect();
        } catch (IOException e) {

        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return JSONObject.parseObject(content.toString());
    }
}
